/**
 * 链接数据库
 * @param indexDBName
 * @param version
 * @param cb
 */
export const openConnect = ( indexDBName:string, cb:any = () => {},version?:number ) => {
    const idb = window.indexedDB.open(indexDBName,version)
    idb.onupgradeneeded = cb // 创建删除表必须使用更新回调
    return new Promise( (resolve, reject) => {
        idb.onsuccess =  (event:Event) => { // 当indexDB请求完成之后可以使用回调进行添加数据
            const idbEvent = (event.target as IDBOpenDBRequest)?.result
            cb(idbEvent)
            resolve(idbEvent)
            idbEvent.close()
        }
        idb.onerror = (event:Event) => {
            const idbEvent = (event.target as IDBOpenDBRequest)?.result
            reject(idbEvent)
            idbEvent.close()
        }
    })
}
/**
 * 删除数据库
 * @param indexDBName 数据库名称
 */
export const deleteDataBase =  (indexDBName:string) => {
    return new Promise((resolve, reject) => {
        const message = window.indexedDB.deleteDatabase(indexDBName)
        resolve(message)
    })
}

/** 获取数据库版本 */
export const getDataBaseVersion = ( dateBaseName:string ) =>
    new Promise( resolve => {
        const idb = window.indexedDB.open(dateBaseName)
        idb.onsuccess = (event) => {
            resolve(Number((event.target as IDBOpenDBRequest)?.result.version))
            const idbEvent = (event.target as IDBOpenDBRequest)?.result
            idbEvent.close()
        }
    })
